package com.lsh.airticket.service.imp;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.PageInfo;
import com.lsh.airticket.dao.AdminDao;
import com.lsh.airticket.entity.Admin;
import com.lsh.airticket.exception.UserException;
import com.lsh.airticket.service.AdminService;
import com.lsh.airticket.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author lsh
 * @date 2021/2/17
 **/
@Service
public class AdminServiceImpl implements AdminService {


    @Autowired
    AdminDao adminDao;

    @Override
    public List<Admin> findAdminList() {
        return adminDao.findTbAdminAll();
    }

    @Override
    public PageInfo<Admin> findByPage() {
        List<Admin> adminAll = adminDao.findTbAdminAll();
        PageInfo<Admin> adminPageInfo = new PageInfo<>(adminAll);
        return adminPageInfo;
    }

    @Override
    public Admin login(Admin admin) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", admin.getUsername());
        Admin adminByCondition = adminDao.findTbAdminByCondition(map);
        if (adminByCondition == null) {
            throw new UserException("用户名不存在");
        }
        String adminSalt = adminByCondition.getAdminSalt();
        if (!adminByCondition.getPassword().equals(DigestUtil.md5Hex(admin.getPassword() + adminSalt))) {
            throw new UserException("密码错误");
        }
        return adminByCondition;
    }

    @Override
    public int register(Admin admin) {
        // 生成盐
        String salt = RandomUtil.randomString(Constants.SALT_SIZE);
        admin.setAdminSalt(salt);
        // 加密密码
        admin.setPassword(DigestUtil.md5Hex(admin.getPassword() +salt));
        admin.setAdminCreatetime(new Date());
        System.out.println(admin);
        int i = adminDao.insertTbAdmin(admin);
        return i;
    }

    @Override
    public int deleteUserById(Integer adminId) {
        return adminDao.deleteTbAdminById(adminId);
    }
}
